﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using GranitePackageSystem.GranitePackagingService;

namespace GranitePackageSystem.Views.Request
{
    public partial class VirtualInstallMachines : Page
    {
        private DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
        GranitePackagingService.Request currentRequest;
        public VirtualInstallMachines()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            checkRoles();
            // Check to make sure there is a current request selected
            if (App.Current.Resources.Contains("Current Request"))
            {
                // Load the current Request
                currentRequest = (GranitePackagingService.Request)App.Current.Resources["Current Request"];

                // Check to see if Step 1 (Provision VM) is complete
                if (currentRequest.VirtStepComplete > MIN_SQL_DATE)
                {
                    busyIndicatorVMS.IsBusy = true;
                    /*
                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.getRequestVirtualMachinesCompleted += new EventHandler<getRequestVirtualMachinesCompletedEventArgs>(proxy_getRequestVirtualMachinesCompleted);
                    proxy.getRequestVirtualMachinesAsync(currentRequest);
                     */
                }
                else
                {
                    enableVMRequest();
                }

                updateNavTable();
            }
            else
            {
                this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
            }
        }

        // #------------------- Step 1 Get Virtual Machine for Testing -------------------------#
        private void enableVMRequest()
        {
            btnRequestVMs.IsEnabled = true;
            disableSourceFileInput();
        }
        private void disableVMRequest()
        {
            btnRequestVMs.IsEnabled = false;
            enableSourceFileInput();
        }

        // ##------------------ Case 1: VM Already Assigned -----------------------------------##       
       /* void proxy_getRequestVirtualMachinesCompleted(object sender, getRequestVirtualMachinesCompletedEventArgs e)
        {
            // Disable Request for additional VMs
            disableVMRequest();

            // Disable Busy Indicator
            busyIndicatorVMS.IsBusy = false;
            
            // Check to see if Step 2: Get Source Files is compeletd
            if (currentRequest.SourceStepComplete > MIN_SQL_DATE)
            {
                // Load the source file step
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getSourceFileObjectCompleted +=new EventHandler<getSourceFileObjectCompletedEventArgs>(proxy_getSourceFileObjectCompleted);
                proxy.getSourceFileObjectAsync(currentRequest.requestID);
            }           
        }*/
        

        // Runs when someone clicks 'Request VM'  This should not happen if the request already has a VM assigned to it
        private void btnRequestVMs_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorVMS.IsBusy = true;

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.requestVMCompleted += new EventHandler<requestVMCompletedEventArgs>(proxy_requestVMCompleted);
            proxy.requestVMAsync(currentRequest);
        }
        void proxy_requestVMCompleted(object sender, requestVMCompletedEventArgs e)
        {
            /*
            blockVMName.Text = e.Result.Name;

            // Save VM to Request
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveVMCompleted += new EventHandler<saveVMCompletedEventArgs>(proxy_saveVMCompleted);
            proxy.saveVMAsync(new VirtualMachine() { Name = e.Result.Name, RequestID = currentRequest.requestID, Status = "Assigned", VirtualMachineID = e.Result.Name });
             */
        }
        /*
        void proxy_saveVMCompleted(object sender, saveVMCompletedEventArgs e)
        {
            disableVMRequest();

            currentRequest.VirtStepComplete = DateTime.UtcNow;
            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request",currentRequest);

            busyIndicatorVMS.IsBusy = true;
            // Update Request to reflect VM Step Complete
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_VM);
            proxy.saveRequestAsync(currentRequest);
        }*/

        void proxy_saveRequestCompleted_VM(object sender, saveRequestCompletedEventArgs e)
        {
            busyIndicatorVMS.IsBusy = false;
        }

        // #------------------- Step 2 Get Source Files ----------------------------------------#

        private void enableSourceFileInput()
        {
            fileUploader.IsEnabled = true;
        }
        private void disableSourceFileInput()
        {
            fileUploader.IsEnabled = false;
            btnAccessVDI.IsEnabled = true;
        }

        // ##------------------ Case 1: Source Files Already Uploaded -------------------------##
        void proxy_getSourceFileObjectCompleted(object sender, getSourceFileObjectCompletedEventArgs e)
        {
            disableSourceFileInput();
        }

        // ##------------------ Case 2: Source Files Newly Uploaded ---------------------------##
        private void fileUploader_Loaded(object sender, RoutedEventArgs e)
        {
            this.fileUploader.Files.SingleFileUploadFinished += new EventHandler<FileUploader.FileUploadedEventArgs>(Files_SingleFileUploadFinished);
            this.fileUploader.Files.AllFilesFinished += new EventHandler(Files_AllFilesFinished);
        }

        void Files_AllFilesFinished(object sender, EventArgs e)
        {
            btnAccessVDI.IsEnabled = true;
            fileUploader.IsEnabled = false;
        }

        // ### ---------------- How to process uploaded Files --------------------------------###
        void Files_SingleFileUploadFinished(object sender, FileUploader.FileUploadedEventArgs e)
        {
            GranitePackagingService.Request req = (GranitePackagingService.Request)App.Current.Resources["Current Request"];
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.processFileAsync(e.FileGuid, e.FileName, req.requestID);
        }
        
        private void updateNavTable()
        {
            DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
            if (App.Current.Resources.Contains("Current Request"))
            {
                GranitePackagingService.Request currentRequest = (GranitePackagingService.Request)App.Current.Resources["Current Request"];
                expanderRequest.Visibility = System.Windows.Visibility.Visible;
                linkVirtualMachines.Visibility = System.Windows.Visibility.Visible;
                if (currentRequest.VirtStepComplete > MIN_SQL_DATE) { linkPackageDetails.Visibility = System.Windows.Visibility.Visible; }
                if (currentRequest.PackageStepComplete > MIN_SQL_DATE) { linkProgramDetails.Visibility = System.Windows.Visibility.Visible; }
                if (currentRequest.AdvertStepComplete > MIN_SQL_DATE) { linkDeploymentPlan.Visibility = System.Windows.Visibility.Visible; }
                if (currentRequest.AdvertStepComplete > MIN_SQL_DATE) { linkLicensing.Visibility = System.Windows.Visibility.Visible; }
            }
            else
            {
                expanderRequest.Visibility = System.Windows.Visibility.Collapsed;

                linkDeploymentPlan.Visibility = System.Windows.Visibility.Collapsed;
                linkLicensing.Visibility = System.Windows.Visibility.Collapsed;
                linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                linkProgramDetails.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void checkRoles()
        {
            Web.User user = WebContext.Current.User;
            bool userInARole = false;

            if (user.IsInRole("GENMILLS\\GPS_Requesters")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_Administrators")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_LicensingApprovers")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_DeploymentApprovers")) { userInARole = true; }

            if (userInARole) { panelContent.Visibility = System.Windows.Visibility.Visible; }
            else { this.NavigationService.Navigate(new System.Uri("/Unauthorized", System.UriKind.Relative)); }
        }
        
        
        private void btnAccessVDI_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("https://vdi.genmills.com"), "_newWindow");
            btnFinished.IsEnabled = true;
        }
        private void btnFinished_Click(object sender, RoutedEventArgs e)
        {
            if (App.Current.Resources.Contains("Current Request"))
            {
                GranitePackagingService.Request currentRequest = (GranitePackagingService.Request)App.Current.Resources["Current Request"];
                currentRequest.VirtStepComplete = DateTime.UtcNow;

                App.Current.Resources.Remove("Current Request");
                App.Current.Resources.Add("Current Request", currentRequest);

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted);
                proxy.saveRequestAsync(currentRequest);

                busyIndicatorVMS.IsBusy = true;
            }
        }
        void proxy_saveRequestCompleted(object sender, saveRequestCompletedEventArgs e)
        {
            busyIndicatorVMS.IsBusy = false;
            this.NavigationService.Navigate(new System.Uri("/Request/PackageDetails", System.UriKind.Relative));
            linkPackageDetails.Visibility = Visibility.Visible;
            updateNavTable();
        }
    }
}
